package tij4.concurrent.source;

/*
    用Executor展示基本的interrupt()用法
 */

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

//sleep()方法进入阻塞状态   ----    可以中断任何要求抛出InterruptedException的调用
//可被中断的阻塞
class SleepBlocked implements Runnable {
    @Override
    public void run() {
        try{
            TimeUnit.SECONDS.sleep(100);
        }catch (InterruptedException e) {
            System.out.println("InterruptedException");
            System.out.println(Thread.currentThread().isInterrupted()); //false
        }
        System.out.println("Exiting SleepBlocked.run()");
    }
}

//IO操作导致阻塞状态    ----    不能中断执行I/O操作的线程
//不可以被中断的阻塞
class IOBlocked implements Runnable {
    private InputStream in;

    public IOBlocked(InputStream in) {
        this.in = in;
    }

    @Override
    public void run() {
        try{
            System.out.println("Waiting for read()");
            in.read();
        }catch (IOException e){
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Interrupted from blocked I/O");
            }else {
                throw  new RuntimeException(e);
            }
        }
        System.out.println("Exiting IOBlocked.run()");
    }
}

//等待锁进入阻塞状态 ----    不能中断试图中获取synchronize锁的线程
//不可以被中断的阻塞
class SynchronizedBlocked implements Runnable {
    public synchronized void f() {
        while (true) {
            Thread.yield();
        }
    }

    public SynchronizedBlocked() {
        new Thread() {
            @Override
            public void run() {
                f();
            }
        }.start();
    }

    @Override
    public void run() {
        System.out.println("Trying to call f()");
        f();
        System.out.println("Exiting SynchronizedBlocked.run()");
    }
}

public class Interrupting {
    private static ExecutorService executorService = Executors.newCachedThreadPool();

    static void test(Runnable r) throws InterruptedException {
        Future<?> submit = executorService.submit(r);
        TimeUnit.MILLISECONDS.sleep(100);
        System.out.println("Interrupting " + r.getClass().getName());
        submit.cancel(true);
        System.out.println("Intrrupt send to "+r.getClass().getName());
    }

    public static void main(String[] args) throws Exception{
        test(new SleepBlocked());
        test(new IOBlocked(System.in));
        test(new SynchronizedBlocked());
        TimeUnit.SECONDS.sleep(3);
        System.out.println("Aborting with System.exit(0)");
        System.exit(0);
    }

}
